
#selenium
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
#反爬
import undetected_chromedriver as uc

from Config import *

import sys

class SeleniumUtil:
    def __init__(self, ProxyInfo=None):
        #逐个信息进行进一步展示
        #反爬插件设置
        chrome_options = uc.ChromeOptions();
        chrome_options.add_argument("--disable-extensions");
        chrome_options.add_argument("--disable-popup-blocking");
        chrome_options.add_argument("--profile-directory=Default");
        chrome_options.add_argument("--ignore-certificate-errors");
        chrome_options.add_argument("--disable-plugins-discovery");
        # chrome_options.add_argument("--incognito");
        chrome_options.add_argument('--no-first-run');
        chrome_options.add_argument('--no-service-autorun');
        chrome_options.add_argument('--no-default-browser-check');
        chrome_options.add_argument('--password-store=basic');
        chrome_options.add_argument('--no-sandbox');

        # 小z添加
        # chrome_options.add_argument('--headless')  # 无头模式，不显示浏览器界面
        # chrome_options.add_argument('--disable-gpu')
        # chrome_options.add_argument('--disable-dev-shm-usage')
        # chrome_options.add_argument('--force-devtools-available')
        # chrome_options.add_argument('--force-fieldtrials=SiteIsolationExtensions/Control')

        # # 设置quick-intensive-throttling-after-loading参数为Disabled
        # chrome_options.add_argument('--throttle-type=Disabled')
        chrome_options.add_argument('--disable-features=CalculateNativeWinOcclusion');

        chrome_options.add_argument('--disable-extensions')  # 禁用扩展程序
        chrome_options.add_argument('--disable-infobars')    # 禁用信息栏
        chrome_options.add_argument('--start-maximized')     # 启动时最大化处理


        #代理信息
        self.ProxyInfo = ProxyInfo;

        #无代理信息
        if self.ProxyInfo==None:
            ProxyOptions = None;
        #有代理信息
        else:
            #代理信息 'http' : 'http://USER:PASSWORD@ENDPOINT', 'https': 'https://192.168.0.6:5418',
            if "USER" in self.ProxyInfo and "PASSWD" in self.ProxyInfo:
                ProxyStr = f'{self.ProxyInfo["USER"]}:{self.ProxyInfo["PASSWD"]}@';
            else:
                ProxyStr = "";
            if "IP" in self.ProxyInfo and "PORT" in self.ProxyInfo:
                ProxyOptions = {
                    'proxy': {
                        'http' : f'http://{ProxyStr}{self.ProxyInfo["IP"]}:{self.ProxyInfo["PORT"]}',
                        'https': f'https://{ProxyStr}{self.ProxyInfo["IP"]}:{self.ProxyInfo["PORT"]}',
                    },
                };
            else:
                ProxyOptions = None;
        
        #增加代理信息
        if ProxyInfo:
            chrome_options.add_argument(f'--proxy-server=http://{ProxyInfo["IP"]}:{ProxyInfo["PORT"]}')
        
        try:
        
            #打开浏览器
            # service = Service(executable_path=Config["Spider"]["workDir"] + '/chromedriver112_0_5615_49.exe')
            # self.driver = uc.Chrome(options=chrome_options, service=service);
            # self.driver = webdriver.Chrome(options=chrome_options, service=service);
            self.driver = uc.Chrome(options=chrome_options);

            # self.driver = uc.Chrome(options=chrome_options, 
            #                         executable_path = Config["Spider"]["workDir"] + '/chromedriver112_0_5615_49.exe');

        except Exception as e:
            print("Chrome Error ", e)
        
		#屏幕最大化
        self.driver.maximize_window();
        #隐式等待1秒
        self.driver.implicitly_wait(1);
        #end
    
    #关闭Selenium
    def Quit(self):
        # 退出模拟浏览器
        try:
            self.driver.quit(); # 一定要退出！不退出会有残留进程！
        except:
            pass;
        #end
    
    #检查浏览器是否可用
    def Check(self):
        #driver未实例化
        if self.driver==None:
            return False;

        try:
            #执行脚本，验证浏览器是否可用
            self.driver.execute_script('javascript:void(0);');
            return True;
        except:
            #异常范围失败
            return  False;
        #end

    #访问特定网页
    def Get(self, URL):
        # 向一个url发起请求
        self.driver.get(URL);
        # 把网页保存为图片，69版本以上的谷歌浏览器将无法使用截图功能
        # driver.save_screenshot("itcast.png")
        # 打印页面的标题
        print(self.driver.title);
        #end

    #获得Selenium driver
    def GetDriver(self):
        return self.driver;
        #end

    #end
 
#检查浏览器是否可用
def CheckDriver(driver):
    #driver未实例化
    if driver==None:
        return False;

    try:
        #执行脚本，验证浏览器是否可用
        driver.execute_script('javascript:void(0);');
        return True;
    except:
        #异常范围失败
        return  False;
    #end

def CheckDriverExit(driver):
    #检查浏览器是否可用
    if CheckDriver(driver)==False:
        try:
            driver.quit();
        except:
            pass;
        sys.exit(1);

#测试模块
if __name__ == "__main__":
    print("selenium >>>>>>>>")

